import { _decorator, Collider, Component, ITriggerEvent } from 'cc';
import { GameManager } from '../framework/GameManager';
import { Constant } from '../framework/Constant';
import { PoolManager } from '../framework/PoolManager';
const { ccclass, property } = _decorator;

const OUTOFBOUNCE = 50;
@ccclass('EnemyPlane')
export class EnemyPlane extends Component {

    public createBulletTime = 0.5;

    private enemySpeed = 0;

    private needBullet = false;

    private currentCreateBulletTime = 0;

    private gameManager: GameManager = null;

    start() {

    }

    protected onEnable(): void {
        const collider = this.getComponent(Collider);
        collider.on('onTriggerEnter', this.triggerEnter, this);
    }
    protected onDestroy(): void {
        const collider = this.getComponent(Collider);
        collider.off('onTriggerEnter', this.triggerEnter, this);
    }

    update(deltaTime: number) {
        const pos = this.node.position;

        const moveLength = pos.z + this.enemySpeed;

        this.node.setPosition(pos.x, pos.y, moveLength)

        if (this.needBullet) {
            this.currentCreateBulletTime += deltaTime;

            if (this.currentCreateBulletTime > this.createBulletTime) {
                this.gameManager.createEnemyBullet(this.node.position);
                this.currentCreateBulletTime = 0
            }
        }

        if (moveLength > OUTOFBOUNCE) {
            // this.node.destroy();
            PoolManager.instance().put(this.node);
        }
    }


    triggerEnter(event: ITriggerEvent) {
        const otherCollider = event.otherCollider.getGroup();
        if (otherCollider === Constant.ColliderType.SELF_BULLET || otherCollider === Constant.ColliderType.SELF_PLANE) {
            this.gameManager.playAudioEffect("enemy");
            // this.node.destroy();
            this.gameManager.createEnemyExplore(this.node.position);
            PoolManager.instance().put(this.node);
            this.gameManager.addScore();
        }
    }

    public setSpeed(gameManager: GameManager, speed: number, needBullet: boolean) {
        this.gameManager = gameManager;
        this.enemySpeed = speed;
        this.needBullet = needBullet;
    }
}

